package com.hluck.goodweatherapp.data.repository;

import android.util.Log;

import androidx.lifecycle.MutableLiveData;

import com.hluck.goodweatherapp.App;
import com.hluck.goodweatherapp.data.bean.MyCity;
import com.hluck.goodweatherapp.data.bean.Province;
import com.hluck.goodweatherapp.data.db.AppDatabase;
import com.hluck.goodweatherapp.utils.LogUtils;

import java.util.List;

import io.reactivex.Completable;
import io.reactivex.Flowable;

/**
 * @Author： LJH
 * @Time： 2024/1/4
 * @description：
 */
public class CityRepository {

    private static final String TAG = "CityRepository";

    private CityRepository() {
    }

    private static final class CityRepositoryHolder{
        private static final CityRepository INSTANCE = new CityRepository();
    }

    public static CityRepository getInstance() {
        return CityRepositoryHolder.INSTANCE;
    }

    /**
     * 获取我的城市所有数据
     * @param listMutableLiveData
     */
    public void getMyCityData(MutableLiveData<List<MyCity>> listMutableLiveData){
        CustomDisposable.addDisposable(App.getDatabase().myCityDao().getAllCity(),listMutableLiveData::postValue);
    }

    /**
     * 添加我的城市数据
     * @param myCity
     */
    public void addMyCityData(MyCity myCity){
        CustomDisposable.addDisposable(App.getDatabase().myCityDao().insertCity(myCity),() -> LogUtils.logD("addMyCityData: 插入数据成功。"));
    }

    /**
     * 删除我的城市数据
     * @param cityName
     */
    public void deleteMyCityData(String cityName){
        CustomDisposable.addDisposable(App.getDatabase().myCityDao().deleteCity(cityName),() -> LogUtils.logD("deleteMyCityData: 删除数据成功"));
    }

    /**
     * 删除我的城市数据
     */
    public void deleteMyCity(MyCity myCity){
        CustomDisposable.addDisposable(App.getDatabase().myCityDao().deleteMyCity(myCity),() -> LogUtils.logD("deleteMyCityData: 删除数据成功"));
    }

    /**
     * 添加城市数据
     * @param cityList
     */
    public void addCityData(List<Province> cityList){
        Province[] provinces = cityList.toArray(new Province[0]);
        Completable insertAll = App.getDatabase().provinceDao().insertAll(provinces);
        CustomDisposable.addDisposable(insertAll, () -> Log.d(TAG, "addCityData: 插入数据成功。"));
    }

    /**
     * 获取城市数据
     */
    public void getCityData(MutableLiveData<List<Province>> listMutableLiveData) {
        Flowable<List<Province>> listFlowable = App.getDatabase().provinceDao().getAll();
        CustomDisposable.addDisposable(listFlowable, listMutableLiveData::postValue);
    }
}
